package com.ruoyi.project.plus.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.plus.bean.SystemMessage;
import com.tencent.cloud.CosStsClient;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

@RestController
@RequestMapping("/app/util")
public class CommonUtilController extends BaseController {
    @ApiOperation("获取腾讯临时上传key")
    @GetMapping("/tencentKey")
    public AjaxResult list()
    {
        TreeMap<String, Object> config = new TreeMap<String, Object>();

        try {
            // 替换为您的 SecretId
            config.put("SecretId", "AKID5PxFfqJJfoxsWukMl5IYHk3HExTjbiN2");
            // 替换为您的 SecretKey
            config.put("SecretKey", "oY5NRs0sVDiJhpyLzOjmiS0MWWHoNrEK");

            // 临时密钥有效时长，单位是秒，默认1800秒，最长可设定有效期为7200秒
            config.put("durationSeconds", 1800);

            // 换成您的 bucket
            config.put("bucket", "ywan-1300416718");
            // 换成 bucket 所在地区
            // config.put("region", "ap-guangzhou");

            // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子：a.jpg 或者 a/* 或者 * 。
            // 如果填写了“*”，将允许用户访问所有资源；除非业务需要，否则请按照最小权限原则授予用户相应的访问权限范围。
            config.put("allowPrefix", "*");

            // 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[] {
                    // 简单上传
                    "name/cos:PutObject",
                    // 表单上传、小程序上传
                    "name/cos:PostObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);

            JSONObject credential = CosStsClient.getCredential(config);
            //成功返回临时密钥信息，如下打印密钥信息
            return AjaxResult.success("获取临时密钥成功",credential.toMap());
        } catch (Exception e) {
            //失败抛出异常
            return AjaxResult.error("no valid secret");
           // throw new IllegalArgumentException("no valid secret !");
        }

    }

    @ApiOperation("文件上传")
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file)
    {
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = "AKID5PxFfqJJfoxsWukMl5IYHk3HExTjbiN2";
        String secretKey = "oY5NRs0sVDiJhpyLzOjmiS0MWWHoNrEK";
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-nanjing");
        ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        String bucketName = "ywan-1300416718";

        int n = 0;
        String filePath = new Date().getTime() + "_" + file.getOriginalFilename();//Md5Utils.hash(file.getName()) + "_" + new Date().getTime() + "." + file.ge;
        String key = filePath;
//        File newFile = new File(filePath);
        try(InputStream in  = file.getInputStream()) {
//            byte[] buffer = new byte[4096];
//            while ((n = in.read(buffer,0,4096)) != -1){
//                os.write(buffer,0,n);
//            }
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(),new ObjectMetadata());;
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            cosClient.shutdown();
            Date expiration = new Date(new Date().getTime() + 5 * 3600 * 10000);
            URL url = cosClient.generatePresignedUrl(bucketName,key,expiration);
            System.out.println(putObjectResult);
            String newUrl = url.toString();
            return AjaxResult.success(newUrl.substring(0,newUrl.indexOf("?")));
        }catch (IOException e){
            e.printStackTrace();
        }
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream());
//        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//        cosClient.shutdown();
//        Date expiration = new Date(new Date().getTime() + 5 * 3600 * 10000);
//        URL url = cosClient.generatePresignedUrl(bucketName,key,expiration);
//        System.out.println(putObjectResult);
//        String newUrl = url.toString();
//        return AjaxResult.success(newUrl.substring(0,newUrl.indexOf("?")));
        return AjaxResult.error("上传失败");
    }
}
